// pages/product/product-detail/index.js
const util = require("../../../../utils/util.js");
const wxParser = require("./../../../../utils/wxParser/index");
const db = wx.cloud.database()
const product = db.collection('shop_product')
const _ = db.command

var app = getApp();

Page({
  data: {
    cartNum: 0,
    current_num: 1,
    color: app.ext.color,
    rgbColor: util.colorRgb(app.ext.color),
    showSku: false,
    type: 0,
    album : [],
    skuHeight: util.rpxToPx(-694) // 购物车弹窗高度
  },
  onLoad: function (options) {
    if(options.id==null||options.id==''){
      const scene = decodeURIComponent(options.scene)
      console.log(scene)
      this.data.id = scene
    }else{
      this.data.id = options.id;
    }
      
      },
  onShow: function () {
    if (this.data.id) {
      this.getDetail(this.data.id);
      this.getAlbum(this.data.id);
    }
    const cart_data = wx.getStorageSync('cart-data') ? JSON.parse(wx.getStorageSync('cart-data')) : [];
    this.setData({
      cartNum: cart_data.length
    })
  },
  getAlbum(id){
    db.collection('shop_product').where({
      _id: _.eq(id)
    }).get().then(res => {

       this.setData({
          album: res.data[0].img_url
        })    
    })
  },
  getDetail(id) {
    db.collection('shop_product').where({
      _id: _.eq(id)
    }).get().then(res => {
      this.defaultSKU(res.data[0]);
      this.init(res.data[0].detail);
      if (res.data.type == 1) {
        this.setData({
          type: 1
        })
      }
     
    })
  },
  // 设置默认规格
  defaultSKU(detailInfo) {
    detailInfo.num = 1;
    detailInfo.skuData = [];
    detailInfo.skuName='';
    detailInfo.skuPrice=-1;
    detailInfo.skuStatus=true;
    let select_sku = {};
    if (detailInfo.gg.pro.length>0) {
      detailInfo.gg.pro.forEach(val => {
        let t = {ggmx:val.ggmx,ggsx:[]}
        let m = val.ggsx.split("#")
        for(var i=0;i<m.length;i++){
          if(i==0){
            t.ggsx.push({ name: m[i], is_select: 1 })
            if(detailInfo.skuName==""||detailInfo.skuName==null){
              detailInfo.skuName = m[i]
            }else{
              detailInfo.skuName = detailInfo.skuName + "-" + m[i]
            }
            
          }else{
            t.ggsx.push({ name: m[i], is_select: 0 })
          }
          
        }
        detailInfo.skuData.push(t)
      })
      detailInfo.gg.con.forEach(val=>{
        if(val.name==detailInfo.skuName){
          detailInfo.skuPrice = val.price
        }
      })
      detailInfo.select_sku = select_sku;
    } else {
      detailInfo.select_sku = select_sku;
    }
    this.setData({
      detailInfo: detailInfo
    })
  },
  iconBtn(e) {
    const type = Number(e.currentTarget.id); // 0：客服 1：收藏 2：购物车
    if (type == 0) {
      console.log('kefu', e);
    }
    if (type == 1) {
      const detailInfo = e.currentTarget.dataset.data;
      if (!detailInfo.collection.id) {
       
      }
      if (detailInfo.collection.id) {
      }
    }
    if (type == 2) {
      wx.switchTab({
        url: '/pages/shop/cart/index'
      })
    }
  },
  hideModal() {
    let _skuHeight = this.data.detailInfo.sku_status ? this.data.skuHeight : util.rpxToPx(-450);
    let animation = wx.createAnimation({
      duration: 200,
      timingFunction: 'linear'
    })
    animation.translateY(0).step();
    this.setData({
      animationData: animation.export()
    })
    setTimeout(() => {
      animation.translateY(_skuHeight).step();
      this.setData({
        animationData: animation.export(),
        showSku: false
      })
    }, 200)
  },
  showModal(e) {
    // 0：加入购物车  1：立即购买
    let _skuHeight = this.data.detailInfo.sku_status ? this.data.skuHeight : util.rpxToPx(-450);
    this.data.is_buynow = Number(e.currentTarget.id);
    let animation = wx.createAnimation({
      duration: 200, // 动画持续时间
      timingFunction: 'linear' // 定义动画效果，当前是匀速
    })
    animation.translateY(0).step();
    this.setData({
      animationData: animation.export(), // 通过export()方法导出数据
      showSku: true
    })
    // 设置setTimeout来改变y轴偏移量，实现有感觉的滑动
    setTimeout(() => {
      animation.translateY(_skuHeight).step();
      this.setData({
        animationData: animation.export()
      })
    }, 200)
  },
  buyNowOrAddCart(e) {
    this.hideModal();
    // 0：加入购物车  1：立即购买
    let detailInfo = e.detail;
    if (this.data.is_buynow) {
      let save_now = [];
      save_now.push(detailInfo);
      console.log(123)
      console.log(save_now)
      wx.setStorageSync('save-now', JSON.stringify(save_now));
      wx.navigateTo({
        url: `../../order/order-add/index`
      })
    } else {
      let cart_data = wx.getStorageSync('cart-data') ? JSON.parse(wx.getStorageSync('cart-data')) : [];
      if (cart_data.length) {
        let sameData = {};
        let index = 0;
        cart_data.forEach((product, i) => {
          if (product._id == detailInfo._id) {
            sameData = product;
            cart_data.splice(i, 1);
            index = i;
          }
        });
        if (sameData._id) {
          sameData.num += detailInfo.num;
          cart_data.splice(index, 0, sameData);
        } else {
          cart_data.push(detailInfo);
        }
      } else {
        cart_data.push(detailInfo);
      }
      wx.setStorageSync('cart-data', JSON.stringify(cart_data));
      this.setData({
        cartNum: cart_data.length
      })
    }
  },
  Share(e) {
    wx.navigateTo({
      // type=1 通过商品详情进入推广图片
      url: `/pages/shop/share/share?type=1&data=${e.currentTarget.dataset.data}`
    });
  },
  onShareAppMessage: function (e) {
    const data = this.data.detailInfo;
    let url = `pages/product/product-detail/index?detail_id=${data.id}`;
    return {
      title: data.name,
      path: url
    };
  },
  init: function (newVal) {
    console.log(newVal);
    wxParser.parse({
      bind: "richText",
      html: newVal,
      target: this,
      enablePreviewImage: false, // 禁用图片预览功能
      tapLink: url => {
        // 点击超链接时的回调函数
        // url 就是 HTML 富文本中 a 标签的 href 属性值
        // 这里可以自定义点击事件逻辑，比如页面跳转
        // wx.navigateTo({
        //     url
        // });
      }
    });
  }
})